package com.example.security;


import com.example.entity.Permission;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

// 设置动态用户信息
@Component
public class MyUserDetailService implements UserDetailsService {

    @Resource
    private UserMapper userMapper;
    /**
     *  1. 根据用户名称查询数据库用户信息
     *  2. 底层会根据数据库查询用户信息判断密码是否正确，security 底层帮我们判断密码是否正确
     *  3. 给用户设置权限
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1. 根据用户名称查询数据库用户信息
        User user=userMapper.findByUsername(username);
        // 3. 给用户设置权限 根据用户名 查询对应的权限
        List<Permission> listPermission = userMapper.findPermissionByUsername(username);
        System.out.println("用户信息:"+user.toString()+"权限信息列表:"+listPermission.toString());
        if(listPermission!=null&&listPermission.size()>0){  //判断权限是否为空
            //定义用户权限
            List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
            for (Permission p:listPermission) {
                authorities.add(new SimpleGrantedAuthority(p.getPermTag()));
            }
            user.setAuthorities(authorities); //给用户设置权限
        }
        return user;
    }
}
